package db.standard;

import org.hibernate.Query;
import org.hibernate.Session;

import db.AbstractService;
import db.nutriment.Nutriment;
import db.nutriment.NutrimentService;
import db.standard.classification.Classification;
import db.standard.classification.ClassificationService;

public class StandardService extends AbstractService<Standard> implements StandardDAO
{
    private ClassificationService classificationService;
    private NutrimentService nutrimentService;
    
    public void setClassificationService(ClassificationService classificationService) {
        this.classificationService = classificationService;
    }
    
    public void setNutrimentService(NutrimentService nutrimentService) {
        this.nutrimentService = nutrimentService;
    }
    
    public void setClassification(Long standardId, Long classificationId) {
        Standard standard = find(standardId);
        Classification classification = classificationService.find(classificationId);
        standard.setClassification(classification);
        insert(standard);
    }
    
    public void setNutriment(Long standardId, Long nutrimentId) {
        Standard standard = find(standardId);
        Nutriment nutriment = nutrimentService.find(nutrimentId);
        standard.setNutriment(nutriment);
        insert(standard);
    }
    
    public Standard findByNutrimentIdAndClassificationId(Long classificationId, Long nutrimentId) {
        Session session = sessionFactory.getCurrentSession();
        try {
            Query query = session.createQuery("from Standard where classification = :cid and nutriment = :nid");
            query.setString("cid", String.valueOf(classificationId));
            query.setString("nid", String.valueOf(nutrimentId));
            return (Standard)query.uniqueResult();
        } finally {
            //session.close();
        }
    }
}
